﻿//using System;
//using System.Diagnostics;
//using System.IO;
//using System.Threading;
//using System.Threading.Tasks;

//namespace MangosRestarter
//{
//    /// <summary>
//    /// 服务器进程监控器，负责监控和自动重启指定进程
//    /// </summary>
//    public class ServerWatcher
//    {
//        public static int CheckIntervalMs = 30000;
//        public string Executable { get; set; }
//        private readonly string displayName;
//        private readonly Action<string> log;
//        private CancellationTokenSource cts;
//        private bool isRunning = false;

//        public ServerWatcher(string exe, string displayName, Action<string> log)
//        {
//            this.Executable = exe;
//            this.displayName = displayName;
//            this.log = log;
//        }

//        /// <summary>
//        /// 启动监控
//        /// </summary>
//        public void Start()
//        {
//            cts = new CancellationTokenSource();
//            Task.Run(() => Worker(cts.Token));
//        }

//        /// <summary>
//        /// 停止监控
//        /// </summary>
//        public void Stop()
//        {
//            cts?.Cancel();
//            cts?.Dispose();
//            cts = null;
//        }

//        /// <summary>
//        /// 手动重启服务器
//        /// </summary>
//        public void Restart()
//        {
//            log($"{displayName} 手动重启请求");
//            isRunning = true;
//            StartServerImmediately();
//        }

//        /// <summary>
//        /// 立即启动服务器进程
//        /// </summary>
//        private void StartServerImmediately()
//        {
//            try
//            {
//                var pname = Path.GetFileNameWithoutExtension(Executable);
//                var processes = Process.GetProcessesByName(pname);

//                if (processes.Length > 0)
//                {
//                    log($"{displayName} 已在运行中，无需重启");
//                    isRunning = true;
//                    return;
//                }

//                //log($"{displayName} 正在启动 {Executable}");
//                var fullPath = ConfigHelper.GetFullPath(Executable);

//                if (!File.Exists(fullPath))
//                {
//                    log($"{displayName} 可执行文件不存在: {fullPath}");
//                    isRunning = false;
//                    return;
//                }

//                Process.Start(new ProcessStartInfo
//                {
//                    FileName = fullPath,
//                    UseShellExecute = false,
//                    CreateNoWindow = false,
//                    WorkingDirectory = Path.GetDirectoryName(fullPath)
//                });

//                isRunning = true;
//                log($"{displayName} 启动成功");
//            }
//            catch (Exception ex)
//            {
//                log($"{displayName} 启动失败：{ex.Message}");
//                isRunning = false;
//            }
//        }

//        /// <summary>
//        /// 监控工作线程
//        /// </summary>
//        private void Worker(CancellationToken token)
//        {
//            while (!token.IsCancellationRequested)
//            {
//                try
//                {
//                    var pname = Path.GetFileNameWithoutExtension(Executable);
//                    var processes = Process.GetProcessesByName(pname);

//                    if (processes.Length == 0 && !isRunning)
//                    {
//                        log($"检测到 {displayName} 未运行，正在启动 {Executable}");
//                        StartServerImmediately();
//                    }
//                    else if (processes.Length > 0)
//                    {
//                        isRunning = true;
//                    }
//                    else
//                    {
//                        isRunning = false;
//                    }
//                }
//                catch (Exception ex)
//                {
//                    log($"{displayName} 监控异常: {ex.Message}");
//                }

//                Thread.Sleep(CheckIntervalMs);
//            }
//        }
//    }
//}

using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace MangosRestarter
{
    /// <summary>
    /// 服务器进程监控器，负责监控和自动重启指定进程
    /// </summary>
    public class ServerWatcher
    {
        public static int CheckIntervalMs = 30000;
        public string Executable { get; set; }
        private readonly string displayName;
        private readonly Action<string> log;
        private CancellationTokenSource cts;
        private bool isRunning = false;
        private DateTime lastResponseTime;
        private const int HangTimeoutMs = 60000; // 60秒无响应认为卡死

        public ServerWatcher(string exe, string displayName, Action<string> log)
        {
            this.Executable = exe;
            this.displayName = displayName;
            this.log = log;
            this.lastResponseTime = DateTime.Now;
        }

        /// <summary>
        /// 启动监控
        /// </summary>
        public void Start()
        {
            cts = new CancellationTokenSource();
            Task.Run(() => Worker(cts.Token));
        }

        /// <summary>
        /// 停止监控
        /// </summary>
        public void Stop()
        {
            cts?.Cancel();
            cts?.Dispose();
            cts = null;
        }

        /// <summary>
        /// 手动重启服务器
        /// </summary>
        public void Restart()
        {
            log($"{displayName} 手动重启请求");
            isRunning = true;
            StartServerImmediately();
        }

        /// <summary>
        /// 更新进程响应时间（用于检测卡死）
        /// </summary>
        public void UpdateResponseTime()
        {
            lastResponseTime = DateTime.Now;
        }

        /// <summary>
        /// 检查进程是否卡死
        /// </summary>
        private bool IsProcessHanged(Process process)
        {
            try
            {
                // 检查进程是否无响应
                if (process != null && !process.HasExited)
                {
                    return process.Responding == false ||
                           (DateTime.Now - lastResponseTime).TotalMilliseconds > HangTimeoutMs;
                }
            }
            catch (Exception ex)
            {
                log($"{displayName} 检查进程状态失败: {ex.Message}");
            }
            return false;
        }

        /// <summary>
        /// 强制终止进程
        /// </summary>
        private void ForceKillProcess(string processName)
        {
            try
            {
                var processes = Process.GetProcessesByName(processName);
                foreach (var proc in processes)
                {
                    try
                    {
                        if (!proc.HasExited)
                        {
                            proc.Kill();
                            proc.WaitForExit(5000);
                            log($"{displayName} 已强制终止卡死进程: {proc.Id}");
                        }
                    }
                    catch (Exception ex)
                    {
                        log($"{displayName} 终止进程失败 {proc.Id}: {ex.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                log($"{displayName} 查找进程失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 立即启动服务器进程
        /// </summary>
        private void StartServerImmediately()
        {
            try
            {
                var pname = Path.GetFileNameWithoutExtension(Executable);
                var processes = Process.GetProcessesByName(pname);

                if (processes.Length > 0)
                {
                    log($"{displayName} 已在运行中，无需重启");
                    isRunning = true;
                    return;
                }

                //log($"{displayName} 正在启动 {Executable}");
                var fullPath = ConfigHelper.GetFullPath(Executable);

                if (!File.Exists(fullPath))
                {
                    log($"{displayName} 可执行文件不存在: {fullPath}");
                    isRunning = false;
                    return;
                }

                Process.Start(new ProcessStartInfo
                {
                    FileName = fullPath,
                    UseShellExecute = false,
                    CreateNoWindow = false,
                    WorkingDirectory = Path.GetDirectoryName(fullPath)
                });

                isRunning = true;
                lastResponseTime = DateTime.Now;
                log($"{displayName} 启动成功");
            }
            catch (Exception ex)
            {
                log($"{displayName} 启动失败：{ex.Message}");
                isRunning = false;
            }
        }

        /// <summary>
        /// 监控工作线程
        /// </summary>
        private void Worker(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                try
                {
                    var pname = Path.GetFileNameWithoutExtension(Executable);
                    var processes = Process.GetProcessesByName(pname);

                    if (processes.Length == 0 && !isRunning)
                    {
                        log($"{displayName} 未运行，正在启动 {Executable}");
                        StartServerImmediately();
                    }
                    else if (processes.Length > 0)
                    {
                        isRunning = true;

                        // 检查每个进程是否卡死
                        foreach (var process in processes)
                        {
                            if (IsProcessHanged(process))
                            {
                                log($"{displayName} 检测到卡死进程 {process.Id}，正在重启...");
                                ForceKillProcess(pname);
                                Thread.Sleep(2000); // 等待2秒让进程完全退出
                                StartServerImmediately();
                                break;
                            }
                        }

                        UpdateResponseTime(); // 更新响应时间
                    }
                    else
                    {
                        isRunning = false;
                    }
                }
                catch (Exception ex)
                {
                    log($"{displayName} 监控异常: {ex.Message}");
                }

                Thread.Sleep(CheckIntervalMs);
            }
        }
    }
}